
package com.suping.springbuckssp.service;

import com.github.pagehelper.PageInfo;
import com.suping.springbuckssp.dao.CoffeeMapper;
import com.suping.springbuckssp.model.Coffee;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author SuPing
 * @date 2022/12/29 12:57
 **/
@Service
@Slf4j
public class CoffeeService {
  private static final String CACHE = "springbucks-coffee";
  @Autowired
  private CoffeeMapper coffeeMapper;
  @Autowired
  private RedisTemplate<String, Coffee> redisTemplate;

  public List<Coffee> findAllCoffee() {
    return coffeeMapper.findAll();
  }

  public Coffee findOneCoffee(String name) {
    HashOperations<String, String, Coffee> hashOperations = redisTemplate.opsForHash();
    if (redisTemplate.hasKey(CACHE) && hashOperations.hasKey(CACHE, name)) {
      log.info("Get coffee {} from Redis.", name);
      return Optional.of(hashOperations.get(CACHE, name)).get();
    }
    Coffee coffee = coffeeMapper.findOneByName(name);
    log.info("Coffee Found: {}", coffee);
    if (coffee!=null) {
      log.info("Put coffee {} to Redis.", name);
      hashOperations.put(CACHE, name, coffee);
      redisTemplate.expire(CACHE, 1, TimeUnit.MINUTES);
    }
    return coffee;
  }

  public List<Coffee> findListByPageHelper(){
    coffeeMapper.findAllWithRowBounds(new RowBounds(1, 3))
        .forEach(c -> log.info("Page(1) Coffee {}", c));
    coffeeMapper.findAllWithRowBounds(new RowBounds(2, 3))
        .forEach(c -> log.info("Page(2) Coffee {}", c));

    log.info("===================");

    coffeeMapper.findAllWithRowBounds(new RowBounds(1, 0))
        .forEach(c -> log.info("Page(1) Coffee {}", c));

    log.info("===================");

    coffeeMapper.findAllWithParam(1, 3)
        .forEach(c -> log.info("Page(1) Coffee {}", c));
    List<Coffee> list = coffeeMapper.findAllWithParam(2, 3);
    PageInfo page = new PageInfo(list);
    log.info("PageInfo: {}", page);
  }

  public List<Coffee> findAllByIds(List<Integer> ids){
    List<Coffee> list=coffeeMapper.findAllWithIds(ids);
    PageInfo page = new PageInfo(list);
    log.info("PageInfo: {}", page);
  }

  public int deleteById( long id){
    return coffeeMapper.deleteByPrimaryKey(id);
  }
}

